package com.lanchewuyou.user.driver.lipeiui;

import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.v4.widget.SwipeRefreshLayout;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.ListView;

import com.lanchewuyou.user.driver.R;
import com.lanchewuyou.user.driver.Utils.TUtils;
import com.lanchewuyou.user.driver.adapter.OrderNoAdapter;
import com.lanchewuyou.user.driver.bean.OrderNoItem;
import com.lanchewuyou.user.driver.modul.Config;
import com.lanchewuyou.user.driver.modul.OkHttpClientManager;
import com.squareup.okhttp.Request;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * 当日订单列表fragment
 */
public class LipeiMainFragment1 extends android.support.v4.app.Fragment implements SwipeRefreshLayout.OnRefreshListener {
    private ListView frgListview1;
    private SwipeRefreshLayout frgRefresh1;
    private List<OrderNoItem> orderNoItemList;
    private ImageView imageView;
    private OrderNoAdapter orderNoAdapter;
    private String url;

    public LipeiMainFragment1() {
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View v = inflater.inflate(R.layout.lipei_main_fragment1, container, false);
        SharedPreferences sharedPreferences = getActivity().getSharedPreferences(Config.PASSWORD_PATH, Activity.MODE_PRIVATE);
        final String driverId = sharedPreferences.getString("driverid", "");
        frgListview1 = (ListView) v.findViewById(R.id.frg1_listview);
        frgRefresh1 = (SwipeRefreshLayout) v.findViewById(R.id.frg1_refresh);
        frgRefresh1.setOnRefreshListener(this);
        frgRefresh1.setColorScheme(R.color.mainred);
        orderNoItemList = new ArrayList<>();
        orderNoAdapter=new OrderNoAdapter(orderNoItemList,getActivity());
        frgListview1.setAdapter(orderNoAdapter);
        imageView = (ImageView) v.findViewById(R.id.frg1_img);
        url = Config.DRIVERORDERLIST + "&page=1&num=20&driverid=" + driverId;
        frgListview1.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                OrderNoItem noItem = orderNoItemList.get(position);
                String itemType = noItem.getType();
                if (itemType.equals("送车订单")) {
                    Intent intent = new Intent(getActivity(), PickCarActivity.class);
                    intent.putExtra("driverid", driverId);
                    intent.putExtra("caseid", noItem.getId());
                    startActivity(intent);
                } else if (itemType.equals("还车订单")) {
                    Intent intent = new Intent(getActivity(), ReturnCarActivity.class);
                    intent.putExtra("driverid", driverId);
                    intent.putExtra("caseid", noItem.getId());
                    startActivity(intent);
                }
            }
        });
        return v;
    }


    @Override
    public void onRefresh() {
       updateData();
    }
    @Override
    public void onResume() {
        super.onResume();
        swipeRefresh(true);
        updateData();
    }

    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case 0:
                    if (frgRefresh1.isRefreshing()){
                        frgRefresh1.setRefreshing(false);
                    }
                    orderNoAdapter.notifyDataSetChanged();
                    break;
                default:
                    break;
            }
        }
    };


    /**
     * swiperefresh在主线程中无法消失，需要新开线程
     *
     * @param refresh
     */
    private void swipeRefresh(final boolean refresh) {
        frgRefresh1.post(new Runnable() {
            @Override
            public void run() {
                if (refresh) {
                    frgRefresh1.setRefreshing(true);
                } else {
                    frgRefresh1.setRefreshing(false);
                }
            }
        });
    }



    private void updateData(){
        OkHttpClientManager.getAsyn(url, new OkHttpClientManager.StringCallback() {
            @Override
            public void onFailure(Request request, IOException e) {
                TUtils.showShort(getActivity(),"服务器出了点问题");
                handler.sendEmptyMessageDelayed(0, 100);
            }

            @Override
            public void onResponse(String response) {
                Log.d("frg", response);
                try {
                    orderNoItemList.clear();
                    JSONObject jsonObject = new JSONObject(response);
                    String status = jsonObject.getString("status");
                    if (status.equals("1")) {
                        JSONObject orders = jsonObject.getJSONObject("orders");
                        int count = orders.getInt("count");
                        if (count == 0) {
                            imageView.setVisibility(View.VISIBLE);
                            handler.sendEmptyMessageDelayed(0, 100);
                        } else {
                            imageView.setVisibility(View.GONE);
                            JSONArray jsonArray = orders.getJSONArray("lists");
                            for (int i = 0; i < jsonArray.length(); i++) {
                                JSONObject item = (JSONObject) jsonArray.get(i);
                                OrderNoItem orderNoItem = new OrderNoItem();
                                String id = item.getString("id");
                                orderNoItem.setId(id);
                                String type = item.getString("huanche");
                                //如果是0，则为送车订单
                                if (type.equals("0")) {
                                    orderNoItem.setAddress(item.getString("address"));
                                    orderNoItem.setType("送车订单");
                                    orderNoItem.setTime(item.getString("jieche_time"));
                                } else if (type.equals("1")) {
                                    orderNoItem.setAddress(item.getString("huanche_address"));
                                    orderNoItem.setType("还车订单");
                                    orderNoItem.setTime(item.getString("expect_huanchetime"));
                                }
                                String payType = item.getString("paid");
                                if (payType.equals("0")) {
                                    orderNoItem.setPayType("线下收费");
                                } else if (payType.equals("1")) {
                                    orderNoItem.setPayType("已收费");
                                }
                                orderNoItemList.add(orderNoItem);
                            }
                            handler.sendEmptyMessageDelayed(0, 100);
                        }
                    } else {
                        handler.sendEmptyMessageDelayed(0, 100);
                        TUtils.showShort(getActivity(), "获取信息失败");
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                    handler.sendEmptyMessageDelayed(0, 100);
                    TUtils.showShort(getActivity(), "服务器出了点问题");
                }
            }
        });
    }
}